package com.hundsun.network.uc.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hundsun.network.uc.vo.Msg4Ws;
import com.hundsun.network.uc.vo.User;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by zhengkk19738 on 2018/5/2.
 */
@Controller
@RequestMapping("/")
public class LoginController {

    @RequestMapping("qr")
    public String index() {
        return "/login/login";
    }


    /**
     * @param userid     用户主键
     * @param secretType 秘钥类型：1：手机号 2：邮箱
     * @param secretKey  秘钥 Userid+手机号/邮箱的md5
     * @param equipId    设备号，二维码唯一标识（来自二维码的回传）
     * @return
     * @Title:二维码登录接口
     * @Description:APP扫一扫后 请求服务器 二维码登录接口
     * @author 张颖辉
     * @date 2018年3月5日上午10:38:57
     */
    // http://192.168.1.110:8080/ssoServer/auth/qrCodeLogin?appid=8a7d0ec2c8184d2aad329c55259bdee4&json={ED:"111111",userid:"00126ac4091749fe8da5e6745d155e7a"}
    @RequestMapping("qrLogin") // CBSA要求必须使用这个名称
    public void qrCodeLogin(String appid, String json, HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        // TODO 关于appid登录渠道暂时不处理

        try {
            // 解析json参数
            ServletOutputStream outputStream = response.getOutputStream();
            // JSONObject 可以解析key缺少双引号的jaon
            JSONObject jsonObject = JSONObject.parseObject(json);
            if (json == null || jsonObject == null) {
                // 因为APP已经完成智能接收这样格式的信息，这里就不单独分装返回的类了
                outputStream.write("{success:false,msg:'json不能为空'}".getBytes());
                outputStream.flush();
                outputStream.close();
                return;
            }
            String userid = jsonObject.getString("userid");
            String equipmentId = jsonObject.getString("ED");

            if (StringUtils.isEmpty(userid)) {
                outputStream.write("{success:false,msg:'userId不能为空'}".getBytes());
                outputStream.flush();
                outputStream.close();
                return;
            }
            if (StringUtils.isEmpty(equipmentId)) {
                outputStream.write("{success:false,msg:'ED不能为空'}".getBytes());
                outputStream.flush();
                outputStream.close();
                return;
            }
            // 保存user到http会话
            // User user = userService.selectUserById(userid);
            /*if (user == null) {
                outputStream.write("{success:false,msg:'user不存在'}".getBytes());
                outputStream.flush();
                outputStream.close();
                return;
            }*/
            String sessionId = equipmentId.split(":")[0];
            String wsId = equipmentId.split(":")[1];
            //  GlobalSessionCache.getInstance().get(sessionId).setAttribute("user", user);
            // request.getSession().setAttribute("user", user);
            // 【推送】通知页面跳转
            Msg4Ws<Boolean> msg4Ws = new Msg4Ws<Boolean>(10001, "登录成功", true);
            String message = new ObjectMapper().writeValueAsString(msg4Ws); // 转为json
            // websocketHandler.sendMsgToUser(wsId, new TextMessage(message));
            // logger.info("推送发送成功");

            // 返回给手机端
            outputStream.write("{success:true,msg:'验证成功啦！'}".getBytes());
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
